package com.todod.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.todod.dto.ProjectInfoDto;
import com.todod.entity.QueryProjectInfo;
import com.todod.entity.ResultData;
import com.todod.mapper.ProjectInfoMapper;
import com.todod.model.Dict;
import com.todod.model.ProjectInfo;
import com.todod.model.User;
import com.todod.service.ICatalogDetailService;
import com.todod.service.ICatalogManageService;
import com.todod.service.IDictService;
import com.todod.service.IUserService;
import com.todod.service.ProjectInfoService;

/**
 * @author lql
 * @date 2020年12月25日
 */
@RestController
@RequestMapping("/projectInfo")
public class ProjectInfoController extends BaseManageController {

	@Autowired
	public ProjectInfoService projectInfoService;
	@Autowired
	public ProjectInfoMapper projectInfoMapper;
	@Autowired
	private IUserService iUserService;
	@Value("${xm.zycp}")
	private String zycp;
	@Value("${xm.jjfa}")
	private String jjfa;
	@Value("${xm.xmkf}")
	private String xmkf;
	@Value("${xm.ptyy}")
	private String ptyy;
	@Value("${xm.wbcp}")
	private String wbcp;
	@Value("${file.upload.path}")
	private String uploadPath;
	@Autowired
	private IDictService iDictService;
	@Autowired
	public ICatalogDetailService catalogDetailService;
	@Autowired
	public ICatalogManageService catalogManageService;

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getListPage")
	public ResultData getListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryProjectInfo queryProjectInfo) {

		IPage<ProjectInfoDto> page = projectInfoService.getListPage(_userId, queryProjectInfo);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/save")
	public ResultData saveData(@RequestAttribute Long _userId, @RequestBody ProjectInfo projectInfo) {

		User user = iUserService.getById(_userId);
		projectInfo.setDepartmentId(user.getDepartid());

		projectInfoService.saveData(_userId, projectInfo);
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/edit")
	public ResultData editData(@RequestAttribute Long _userId, @RequestBody ProjectInfo projectInfo) {

		projectInfoService.editData(_userId, projectInfo);
		return ResultData.success();
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	public ResultData delete(String ids) {

		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			projectInfoMapper.deleteById(id[i]);
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/complete")
	public ResultData complete(@RequestAttribute Long _userId, String ids) {

		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			projectInfoService.complete(_userId, id[i]);
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/submit")
	public ResultData submit(@RequestAttribute Long _userId, String ids) {

		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			projectInfoService.submit(_userId, id[i]);
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getInfo")
	public ResultData getInfo(Long code) {
		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}
		return ResultData.success("ok", projectInfoService.getInfo(code));
	}

	/**
	 * @Title: getSortNumByType
	 * @Description:根据项目类型获得项目编号
	 * @author: dyl
	 * @date 2020-03-15
	 * @param type
	 * @return
	 */
	@GetMapping("/getSortNumByType")
	public ResultData getSortNumByType(@RequestAttribute Long _userId, HttpSession session, String type) {

		User user = iUserService.getById(_userId);

		ProjectInfo projectInfo = projectInfoService.getSortNumByType(type, user.getDepartid());

		int sort = 0;
		String code = "";
		String flag = "";

		if (type != null && type.equalsIgnoreCase("1")) {
			flag = zycp;
		} else if (type != null && type.equalsIgnoreCase("2")) {
			flag = jjfa;
		} else if (type != null && type.equalsIgnoreCase("3")) {
			flag = xmkf;
		} else if (type != null && type.equalsIgnoreCase("4")) {
			flag = ptyy;
		} else if (type != null && type.equalsIgnoreCase("5")) {
			flag = wbcp;
		}

		if (projectInfo != null) {
			String maxSort = projectInfo.getSortNum();
			if (maxSort != null) {
				String num = maxSort.substring(1, maxSort.length());
				sort = Integer.valueOf(num) + 1;
				if (sort < 10) {
					code = flag + "000" + sort;
				} else if (sort < 100) {
					code = flag + "00" + sort;
				} else if (sort < 1000) {
					code = flag + "0" + sort;
				} else {
					code = flag + sort;
				}
			}
		} else {
			code = flag + "0001";
		}

		return ResultData.success("ok", code);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getXiangMuList")
	public ResultData getXiangMuList(@RequestAttribute Long _userId) {

		User user = iUserService.getById(_userId);

		List<ProjectInfo> list = projectInfoService.getXiangMuList(user.getRoleId());
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getYSPPage")
	public ResultData getYSPPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryProjectInfo queryProjectInfo) {

		IPage<ProjectInfoDto> page = projectInfoService.getYSPPage(_userId, queryProjectInfo);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/backTo")
	public ResultData backTo(@RequestAttribute Long _userId, Long code) {

		projectInfoService.backTo(_userId, code);
		return ResultData.success();
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getXiangMuTypes")
	public ResultData getXiangMuTypes() {

		List<Dict> list = iDictService.getDictListByCode("YW_XIANGMU_TYPE");

		List<ProjectInfo> list2 = new ArrayList<ProjectInfo>();
		ProjectInfo projectInfo = new ProjectInfo();
		projectInfo.setId(1l);
		projectInfo.setTypeName("项目类型");

		List<ProjectInfo> children = new ArrayList<ProjectInfo>();
		for (Dict dict : list) {
			ProjectInfo projectInfo1 = new ProjectInfo();
			projectInfo1.setId(Long.valueOf(dict.getCode()));
			projectInfo1.setTypeName(dict.getName());
			projectInfo1.setParentId(1l);

			children.add(projectInfo1);
		}

		projectInfo.setChildren(children);

		list2.add(projectInfo);

		return ResultData.success("ok", list2);
	}

	/**
	 * @Title: downLoad
	 * @Description: 附件下载
	 * @author lql
	 * @date 2021年3月1日
	 * @return ResponseEntity响应的头文件信息，具体信息
	 */
	@RequestMapping(value = "/downLoad", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public void downLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") Long xiangmuId) {

		// 获取项目数据
		ProjectInfo projectInfo = projectInfoMapper.selectById(xiangmuId);

		String path = uploadPath + File.separator + "static" + File.separator + "zip";

		try {
			long timeMillis = System.currentTimeMillis();

			// 创建一个file实例对象，指向文件路径（存放照片的根目录）
			File rootFile = new File(path + File.separator + timeMillis);
			// 创建根目录【必须实际创建文件夹，否则会在new
			if (!rootFile.exists()) {
				// 创建新文件夹，可以多层（mkdir()创建新文件夹，只能创建一层）
				rootFile.mkdirs();
			}

			projectInfoService.getChildrens(response, xiangmuId, rootFile);

			// 创建文件输出流（zip流对象）【实际创建了zip文件，0kb】
			FileOutputStream fos1 = new FileOutputStream(
					new File(path + "/" + projectInfo.getXiangmumingcheng() + ".zip"));

			response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
			response.setHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode(projectInfo.getXiangmumingcheng(), "UTF-8") + ".zip");
			response.setHeader("Content-Type", "application/zip");

			// 将要被压缩的文件夹路径
			String folderPath = path + File.separator + timeMillis;

			ZipOutputStream zos = null;
			ServletOutputStream os = null;
			ByteArrayOutputStream baos = null;
			try {
				zos = new ZipOutputStream(fos1);

				os = response.getOutputStream();

				// 递归遍历整个文件夹并添加到压缩包
				addFolderToZip("", new File(folderPath), zos);

				InputStream inStream = new FileInputStream(
						new File(path + "/" + projectInfo.getXiangmumingcheng() + ".zip"));
				byte[] buffer = new byte[1024];
				int len;
				baos = new ByteArrayOutputStream();
				while ((len = inStream.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				os = response.getOutputStream();
				os.write(baos.toByteArray());
			} finally {
				zos.flush();
				zos.close();
				fos1.close();
				baos.flush();
				baos.close();
				os.flush();
				os.close();
			}

			// 删除文件和压缩文件
			// delFolder(fileStr);
			// delFolder(zipFileStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将文件夹及其中的文件递归添加到压缩流中
	 *
	 * @param parentPath 父级路径
	 * @param folder     文件夹
	 * @param zos        Zip输出流
	 * @throws FileNotFoundException 文件未找到异常
	 * @throws IOException           IO异常
	 */
	private static void addFolderToZip(String parentPath, File folder, ZipOutputStream zos)
			throws FileNotFoundException, IOException {
		for (File file : folder.listFiles()) {
			if (file.isDirectory()) {
				// 递归添加子文件夹中的文件
				addFolderToZip(parentPath + folder.getName() + "/", file, zos);
			} else {
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(file);

					// 新建Zip条目并将输入流加入到Zip包中
					ZipEntry zipEntry = new ZipEntry(parentPath + folder.getName() + "/" + file.getName());
					zos.putNextEntry(zipEntry);

					byte[] bytes = new byte[1024];
					int length;
					while ((length = fis.read(bytes)) >= 0) {
						zos.write(bytes, 0, length);
					}
				} finally {
					if (fis != null) {
						fis.close();
					}
				}
			}
		}
	}

}
